#!/usr/bin/python3
import re
import sys
import cv2
import numpy as np
from fastapi import FastAPI, Request
from fastapi.encoders import jsonable_encoder
from fastapi.responses import JSONResponse

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import NoSuchElementException        
from selenium.common.exceptions import TimeoutException        

#Disabling docs
app = FastAPI(docs_url=None)

#Defining chrome web driver

#Regex for email addresses
regex = re.compile(r'([A-Za-z0-9]+[.-_])*[A-Za-z0-9]+@[A-Za-z0-9-]+(\.[A-Z|a-z]{2,})+')

#Function check_pwn() sending data to HaveIBeenPwned
def check_pwn(email):
    url = "https://haveibeenpwned.com/"
    global hermes
    hermes = webdriver.Chrome('./driver/chromedriver')
    hermes.get(url)
    search_bar = hermes.find_element(By.XPATH, '//*[@id="Account"]')
    search_bar.send_keys(email)
    search_bar.send_keys(Keys.RETURN)
    WebDriverWait(hermes, 5).until(EC.presence_of_element_located((By.XPATH, '//*[@id="pwnCount"]/a[1]')))
    text_to_get = hermes.find_element(By.XPATH, '/html/body/div[4]/div[1]/div/div/div[1]/p')
    final_text = text_to_get.text
    hermes.close()
    return final_text
    
#Main function checks if email is in valid format or fail
@app.get("/email/{email}")
async def read_email(email):
    if re.fullmatch(regex, email):
        return check_pwn(email)
    else:
        return [{"Please enter valid email address"}]

#Handling error 500 if target is not vulnerable
@app.exception_handler(500)
async def internal_exception_handler(request: Request, exc: Exception):
    hermes.close()
    return JSONResponse(status_code=500, content=jsonable_encoder({"code": 500, "msg": "Internal Server Error. Seems like target is not vulnerable"}))
